"""
生成诸如int a, b=2;类似的变量定义
解析成：
UnaryOp('int', BlockOp([Identifier(a), BinaryOp('=', Identifier(b), Number(2))]))
所以要放在flatten_comma后面
"""


from ..core.dslc_parser import ASTNode, Identifier, UnaryOp, BinaryOp, BlockOp, String
from ..core.dslc_symbol_table import SymbolTable

VAR_KWS = ['int', 'float', 'double']

VAR_ATTR = ['unsigned', 'extern', 'volatile']


def merge_var_name_pass(top: ASTNode):
    if isinstance(top, Identifier):
        for kw in VAR_KWS:
            if top.name.endswith(kw):
                return 1
    return 0


def is_var_define_block(top: ASTNode):
    if isinstance(top, BlockOp):# and len(top.oplist) > 1:
        if isinstance(top.oplist[0], Identifier):
            for kw in VAR_KWS:
                if top.oplist[0].name.endswith(kw):
                    print('============>', top)
                    return True
            return False
        else:
            return False
    return False


def unary_var_define_pass(stab: SymbolTable, top: BlockOp):
    '''这里只负责表达式的处理不负责符号表的操作'''
    if len(top.oplist) > 1:
        retblk = top.oplist[1] if isinstance(top.oplist[1], BlockOp) else BlockOp([top.oplist[1]])
        return UnaryOp(top.oplist[0].name, retblk)
    else:
        print('------------>', top)
        #作为type cast中应用的
        return UnaryOp(top.oplist[0].name, String('Blank'))


def append_attr_pass(stab: SymbolTable, top: BlockOp):
    opidx = -1
    oplen = len(top.oplist)
    oplist = []
    while opidx < oplen-1:
        opidx = opidx + 1
        _op = top.oplist[opidx]
        if not isinstance(_op, Identifier):
            oplist.append(_op)
            continue
        #
        #print(top.oplist)
        if _op.name in VAR_ATTR:
            typestr = _op.name
            opidx = opidx + 1
            _op = top.oplist[opidx]
            while isinstance(_op, Identifier) and (_op.name in VAR_ATTR or _op.name in VAR_KWS):
                typestr += ' ' + _op.name
                opidx = opidx + 1
                if opidx < len(top.oplist):
                    _op = top.oplist[opidx]
                else:
                    break
            oplist.append(Identifier(typestr))
            #回到不是attr或vardef的位置
            opidx = opidx - 1
        else:
            oplist.append(_op)
    return BlockOp(oplist)
